package com.dongdong.bookstore.security.model;

import cn.hutool.core.collection.CollUtil;
import com.dongdong.bookstore.module.ums.model.Resource;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chiangkai
 * @date 2021-09-19
 * @email chiangkk@163.com
 */
@Data
public class CustomUserDetails implements UserDetails {
    private CustomUser customUser;
    private List<Resource> resourceList;

    public CustomUserDetails(CustomUser customUser, List<Resource> resourceList) {
        this.customUser = customUser;
        if (resourceList != null) {
            this.resourceList = resourceList;
        } else {
            // 防止空指针异常
            this.resourceList = new ArrayList<Resource>();
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return resourceList.stream().map(role -> new SimpleGrantedAuthority(role.getId() + ":" + role.getName())).collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return customUser.getPassword();
    }

    @Override
    public String getUsername() {
        return customUser.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return customUser.getStatus().equals(1);
    }
}
